package com.sen.common.feign.config;

import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sen.common.common.bo.PeopleInfo;
import com.sen.common.common.constrant.CommonConstrant;
import com.sen.common.common.util.JacksonUtils;
import com.sen.common.tenant.config.TenantContextHolder;
import com.sen.common.user.config.UserContextHolder;
import feign.Logger;
import feign.RequestInterceptor;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;

import java.nio.charset.Charset;

/**
 *
 * @author esjiang
 */
public class FeignInterceptorConfig {

    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL ;
    }

    @Bean
    public RequestInterceptor baseFeignInterceptor() {
        return template -> {
            /** mdc追踪 */
            String traceId = MDC.get(CommonConstrant.TRACE_NAME);
            if (StrUtil.isNotEmpty(traceId)) {
                template.header(CommonConstrant.X_TRACE_HEADER, traceId);
            }
            /** 租户下沉 */
            String tenantCode = TenantContextHolder.getTenant();
            if (StrUtil.isNotEmpty(tenantCode)){
                template.header(CommonConstrant.X_TENANT_HEADER,tenantCode) ;
            }
            /** 账户名 */
            String userName = UserContextHolder.getUser() ;
            if (StrUtil.isNotEmpty(userName)){
                template.header(CommonConstrant.X_USER_HEADER,URLEncoder.createDefault().encode(userName,Charset.forName("utf-8"))) ;
            }
            PeopleInfo people = UserContextHolder.getPeople();
            if (ObjectUtil.isNotNull(people)){
                String jsonString = JacksonUtils.toJSONString(people);
                if (StrUtil.isNotBlank(jsonString)){
                    jsonString = URLEncoder.createDefault().encode(jsonString, Charset.forName("utf-8"));
                }
                template.header(CommonConstrant.X_PEOPLE_HEADER, jsonString) ;
            }
        };
    }
}
